package com.yanq.liancar.activity;
/*
 *  @创建者     liyan
 *  @创建时间   2018/9/27  15:57
 *  @描述       ${TODO}
 */


import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.CountNotNewCarPriceBean;
import com.yanq.liancar.bean.Json1Bean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.bean.UserBindBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CarSellingActivity extends BaseToolbarActivity {
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_chexing)
    EditText tvChexing;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.et_mileage)
    EditText etMileage;
    @BindView(R.id.et_buyprice)
    EditText etBuyprice;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_subm)
    TextView tvSubm;
    @BindView(R.id.rb_jiaohao)
    RadioButton rbJiaohao;
    @BindView(R.id.rb_lianghao)
    RadioButton rbLianghao;
    @BindView(R.id.rb_yiban)
    RadioButton rbYiban;
    @BindView(R.id.rb_jiaocha)
    RadioButton rbJiaocha;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;

    private List<String> options1Items = new ArrayList<>();
    private List<Json1Bean> options1Items1 = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private int type=1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_carselling);
        ButterKnife.bind(this);
        Utils.setStatusBar(this, true, false);
        mTvTitle.setText("高价卖车");

        new Thread(new Runnable() {
            @Override
            public void run() {
                initJsonData1();
            }
        }).start();

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.rb_jiaocha:
                        type=1;
                        break;
                    case R.id.rb_yiban:
                        type=2;
                        break;
                    case R.id.rb_lianghao:
                        type=3;
                        break;
                    case R.id.rb_jiaohao:
                        type=4;
                        break;
                }
            }
        });
    }

    @OnClick({R.id.tv_address, R.id.tv_time, R.id.tv_subm})
    public void onViewClicked(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        switch (view.getId()) {
            case R.id.tv_address:
                // 隐藏软键盘
                showPickerView();
                break;
            case R.id.tv_time:
                yearPickerView();
                break;
            case R.id.tv_subm:
                if (isNull()) {
                    getUserStatus();
                }
                break;

        }
    }

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items1.get(options1).getPickerViewText() + "-" +
                        options2Items.get(options1).get(options2) + "-" +
                        options3Items.get(options1).get(options2).get(options3);
                //                province=options1Items1.get(options1).getArea_id();
                //                city=options1Items1.get(options1).getChild().get(options2).getArea_id();
                //                county=options1Items1.get(options1).getChild().get(options2).getChild().get(options3).getArea_id();

                tvAddress.setText(tx);

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData1() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = getJson(this, "json.json");//获取assets目录下的json文件数据

        ArrayList<Json1Bean> jsonBean = parseData1(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items1 = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> provilist = new ArrayList<>();
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            provilist.add(jsonBean.get(i).getArea_name());

            for (int c = 0; c < jsonBean.get(i).getChild().size(); c++) {//遍历该省份的所有城市
                //                String CityName = ;
                CityList.add(jsonBean.get(i).getChild().get(c).getArea_name());//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getChild().get(c).getChild() == null
                        || jsonBean.get(i).getChild().get(c).getChild().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (int j = 0; j < jsonBean.get(i).getChild().get(c).getChild().size(); j++) {
                        City_AreaList.add(jsonBean.get(i).getChild().get(c).getChild().get(j).getArea_name());
                    }

                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            options1Items.addAll(provilist);
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

    }

    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public ArrayList<Json1Bean> parseData1(String result) {//Gson 解析
        ArrayList<Json1Bean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                Json1Bean entity = gson.fromJson(data.optJSONObject(i).toString(), Json1Bean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    private void yearPickerView() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        //正确设置方式 原因：注意事项有说明
        startDate.set(1990, 0, 1);
        endDate.set(2050, 11, 31);


        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {

                String Startdate = getTime(date);
                tvTime.setText(Startdate);

            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择时间")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.main_color))//取消按钮文字颜色
                .setTitleBgColor(0xFFd6d6d6)//标题背景颜色 Night mode
                .setBgColor(0xFFffffff)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .setBgColor(0xFFffffff)
                .build();
        pvTime.show();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private void getUserStatus() {
        OkGo.<String>post(Config.s + "llc/notNewCarController/countNotNewCarPrice")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .params("resetPrice", etBuyprice.getText().toString().trim())
                .params("mileage", etMileage.getText().toString().trim())
                .params("carCondition", type)
                .params("address", tvAddress.getText().toString().trim())
                .params("startTime", tvTime.getText().toString().trim())
                .params("carType", tvChexing.getText().toString().trim())
                .params("tel", etPhone.getText().toString().trim())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.e("11111111111", response.body().toString());
                        if (!response.equals("")) {
                            Gson gson = new Gson();
                            CountNotNewCarPriceBean bean = gson.fromJson(response.body(), CountNotNewCarPriceBean.class);
                            if (bean.isIsSuccess()) {
                                Bundle bundle=new Bundle();
                                bundle.putString("price",bean.getData()+"");
                                RxActivityTool.skipActivity(mContext, EvaluationResultsActivity.class,bundle);
                            } else {
                                RxToast.error(bean.getOutputMessage());
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        RxToast.error("服务器连接失败");
                        LogUtils.e("asdasdad", response.code() + "");
                        LogUtils.e("asdasdad", response.message() + "");
                        super.onError(response);
                    }
                });
    }

    private boolean isNull() {
        if (TextUtils.isEmpty(tvAddress.getText().toString().trim())) {
            RxToast.error("请选择卖车地点");
            return false;
        } else if (TextUtils.isEmpty(tvTime.getText().toString().trim())) {
            RxToast.error("请选择卖车时间");
            return false;
        } else if (TextUtils.isEmpty(tvChexing.getText().toString().trim())) {
            RxToast.error("请输入车型");
            return false;
        } else if (TextUtils.isEmpty(etMileage.getText().toString().trim())) {
            RxToast.error("请输入行驶里程");
            return false;
        } else if (TextUtils.isEmpty(etBuyprice.getText().toString().trim())) {
            RxToast.error("请输入购买价格");
            return false;
        } else if (TextUtils.isEmpty(etPhone.getText().toString().trim())) {
            RxToast.error("请输入接受手机");
            return false;
        }
        return true;
    }
}
